package cn.stylefeng.guns.modular.business.frequency.syssite.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.custom.constant.PublicCommon;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.result.PkgLinkman;
import cn.stylefeng.guns.modular.business.frequency.syssite.entity.SysSite;
import cn.stylefeng.guns.modular.business.frequency.syssite.model.result.*;
import cn.stylefeng.guns.modular.business.frequency.syssite.service.SysSiteService;
import cn.stylefeng.guns.modular.business.frequency.userawardbase.entity.UserAwardBase;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.EasyExcelUtil;
import cn.stylefeng.guns.sys.modular.emp.entity.SysEmp;
import cn.stylefeng.guns.sys.modular.emp.mapper.SysEmpMapper;
import cn.stylefeng.guns.sys.modular.org.entity.SysOrg;
import cn.stylefeng.guns.sys.modular.org.service.SysOrgService;
import cn.stylefeng.guns.sys.modular.user.entity.SysTenant;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.mapper.SysUserMapper;
import cn.stylefeng.guns.sys.modular.user.service.SysTenantService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * sys_site 控制器
 *
 * @author: yujie
 * @date: 2023/05/09 17:17
 */
@RestController
@RequestMapping("/api/site")
public class SysSiteController {

    @Resource
    private SysSiteService siteService;
    @Autowired
    private SysOrgService sysOrgService;

    @GetMapping
    @ApiOperation(value = "网点管理列表")
    @PreAuthorize("@el.check('site:list')")
    public ResponseData getSiteListPage(@ApiParam(value = "查询月份，格式：yyyyMM") @RequestParam(value = "month", required = false) String month,
                                                   SiteDTO siteDTO) {
        List<PkgSite> list = siteService.getSiteList(month, siteDTO);
        SiteSummaryVO siteSummaryVO = new SiteSummaryVO();
        PkgSite summary = new PkgSite();
        summary.setCreateFee(list.stream().filter(a -> a.getCreateFee() != null).map(PkgSite::getCreateFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setCreateCount(list.stream().filter(a -> a.getCreateCount() != null).map(PkgSite::getCreateCount).reduce(Long::sum).orElse(0L));
        summary.setPickFreeFee(list.stream().filter(a -> a.getPickFreeFee() != null).map(PkgSite::getPickFreeFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setPickFreeCount(list.stream().filter(a -> a.getPickFreeCount() != null).map(PkgSite::getPickFreeCount).reduce(Long::sum).orElse(0L));
        summary.setPickFee(list.stream().filter(a -> a.getPickFee() != null).map(PkgSite::getPickFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setPickCount(list.stream().filter(a -> a.getPickCount() != null).map(PkgSite::getPickCount).reduce(Long::sum).orElse(0L));
        summary.setVerifyFee(list.stream().filter(a -> a.getVerifyFee() != null).map(PkgSite::getVerifyFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setVerifyCount(list.stream().filter(a -> a.getVerifyCount() != null).map(PkgSite::getVerifyCount).reduce(Long::sum).orElse(0L));
        summary.setTransportFee(list.stream().filter(a -> a.getTransportFee() != null).map(PkgSite::getTransportFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setTransportCount(list.stream().filter(a -> a.getTransportCount() != null).map(PkgSite::getTransportCount).reduce(Long::sum).orElse(0L));
        summary.setSignFee(list.stream().filter(a -> a.getSignFee() != null).map(PkgSite::getSignFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setSignCount(list.stream().filter(a -> a.getSignCount() != null).map(PkgSite::getSignCount).reduce(Long::sum).orElse(0L));
        summary.setDeliveryFee(list.stream().filter(a -> a.getDeliveryFee() != null).map(PkgSite::getDeliveryFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setDeliveryCount(list.stream().filter(a -> a.getDeliveryCount() != null).map(PkgSite::getDeliveryCount).reduce(Long::sum).orElse(0L));
        summary.setRoyaltyFee(list.stream().filter(a -> a.getRoyaltyFee() != null).map(PkgSite::getRoyaltyFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        summary.setRoyaltyCount(list.stream().filter(a -> a.getRoyaltyCount() != null).map(PkgSite::getRoyaltyCount).reduce(Long::sum).orElse(0L));
        summary.setLineCount(list.stream().filter(a -> a.getLineCount() != null).map(PkgSite::getLineCount).reduce(Long::sum).orElse(0L));
        summary.setCompanyCount(list.stream().filter(a -> a.getCompanyCount() != null).map(PkgSite::getCompanyCount).reduce(Long::sum).orElse(0L));
        siteSummaryVO.setList(list);
        siteSummaryVO.setSummary(summary);
        return ResponseData.andaSuccess(siteSummaryVO);
    }

    @GetMapping("/{id}/company")
    @ApiOperation(value = "网点客户供应商分页列表")
    public ResponseData getCompanyList(@PathVariable String id) {
        Page<PkgLinkman> list = siteService.getCompanyLinkmanList(id);
        SiteDTO siteDTO = new SiteDTO();
        siteDTO.setAsc(false);
        siteDTO.setColumn("id");
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list,siteDTO));
    }

    @GetMapping("/simple")
    @ApiOperation(value = "所有网点列表【网点ID，name，用于其他模块下拉展示】")
    public ResponseData getSimpleSiteList() {
        List<SimpleSiteVO> list = siteService.getSimpleSiteList();
        return ResponseData.andaSuccess(list);
    }

    @GetMapping("/all")
    @ApiOperation(value = "所有网点列表【完整信息】")
    public ResponseData getAllSiteList(SysSite site) {
        List<SysSite> list = siteService.getAllSiteList(site);
        return ResponseData.andaSuccess(list);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "网点详情")
    public ResponseData getSiteDetail(@PathVariable String id) {
        PkgSite site = siteService.getSiteDetail(id);
        return ResponseData.andaSuccess(site);
    }

    @PostMapping
    @ApiOperation(value = "网点新增")
    @PreAuthorize("@el.check('site:add')")
    public ResponseData addSite(@Validated @RequestBody SysSite site) {
        StringBuilder errorMsg = new StringBuilder();
        if (!siteService.checkSiteAdd(site, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        siteService.add(site);
        return ResponseData.andaSuccess();
    }


    @PostMapping("tenantIdardAdd")
    @ApiOperation(value = "网点提成新增")
    public ResponseData addSiteAward(@Validated @RequestBody SysSite site) {
        siteService.addSiteAward(site);
        return ResponseData.andaSuccess();
    }


    @PostMapping("/userAwardList")
    @ApiOperation(value = "网点提成查询")
    public ResponseData userAwardList(@Validated @RequestBody SysSite site) {
        return ResponseData.andaSuccess(siteService.userAwardList(site));
    }

    @PostMapping("/userAwardDelelt")
    @ApiOperation(value = "网点提成删除")
    public ResponseData userAwardDelelt(@Validated @RequestBody UserAwardBase site) {
        siteService.userAwardDelelt(site.getId());
        return ResponseData.andaSuccess();
    }

    @PostMapping("/userAwardUpdate")
    @ApiOperation(value = "网点提成编辑")
    public ResponseData userAwardUpdate(@Validated @RequestBody UserAwardBase site) {
        siteService.userAwardUpdate(site);
        return ResponseData.andaSuccess();
    }






    @PutMapping
    @ApiOperation(value = "网点编辑")
    @PreAuthorize("@el.check('site:edit')")
    public ResponseData updateSite(@RequestBody SysSite site) {
        StringBuilder errorMsg = new StringBuilder();
        if (!siteService.checkSiteUpdate(site, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        siteService.updateSite(site);
        return ResponseData.andaSuccess();
    }

    @Autowired
    private SysEmpMapper sysEmpMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @ApiOperation(value = "网点删除")
    @DeleteMapping("/{id}")
    public ResponseData delete(@PathVariable String id) {
        StringBuilder errorMsg = new StringBuilder();
        if (!siteService.checkSiteDelete(id, errorMsg)) {
            return ResponseData.andaError(errorMsg.toString());
        }
        SysSite sysSite = siteService.getById(id);
        //删除部门
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setIsSite(1);
//        sysOrg.setId(sysSite.getOrgId());
//        sysOrgService.updateById(sysOrg);
        sysOrgService.removeById(sysSite.getOrgId());

        //删除网点下的用户
        //获取网点下所有用户
        List<SysEmp> sysEmps = sysEmpMapper.selectList(new LambdaQueryWrapper<SysEmp>()
                .eq(SysEmp::getOrgId, sysSite.getOrgId()));
        if (CollectionUtil.isNotEmpty(sysEmps)) {
            List<Long> userIds = sysEmps.stream().map(SysEmp::getId).collect(Collectors.toList());
            sysUserMapper.update(null, new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getStatus, PublicCommon.删除)
                    .in(SysUser::getId, userIds));
        }

        siteService.deleteSite(id);

        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "网点用户列表")
    @GetMapping("/{id}/user")
    public ResponseData getUserList(@PathVariable String id) {
        return siteService.getUserList(id);
    }

    @ApiOperation(value = "网点奖励明细导出")
    @GetMapping("/export/bonus")
    public void exportBonusDetail(HttpServletResponse response,
                                  @ApiParam(value = "查询月份，格式：yyyyMM") @RequestParam(value = "month") String month) throws Exception {
        EasyExcelUtil.export2Web(response, month + "网点奖励明细", "sheet1",
                SiteBonusExport.class, siteService.getSiteBonusList(month));
    }

    @ApiOperation(value = "网点提成明细导出")
    @GetMapping("/export/royalty")
    public void exportRoyaltyDetail(HttpServletResponse response,
                                    @ApiParam(value = "查询月份，格式：yyyyMM") @RequestParam(value = "month") String month) throws Exception {
        EasyExcelUtil.export2Web(response, month + "网点提成明细", "sheet1",
                SiteRoyaltyExport.class, siteService.getSiteRoyaltyList(month));
    }

    @ApiOperation(value = "网点供应商导出")
    @GetMapping("/{id}/export")
    public void exportExcel(@PathVariable String id, HttpServletResponse response) throws Exception {
        SysSite site = siteService.getById(id);
        EasyExcelUtil.export2Web(response, site.getName() + "网点供应商联系人数据", "sheet1",
                SiteCompanyLinkmanExport.class, siteService.getCompanyExportData(id));
    }


    //<editor-fold desc="合同签章图片管理">

    @Resource
    private SysTenantService sysTenantService;

    @Resource
    private BusinessUtil businessUtil;


    @ApiOperation(value = "合同签章图片查询")
    @GetMapping("/contractSigning/query")
    public ResponseData queryContractSigning()  {
        SysTenant tenant = sysTenantService.getOne(new LambdaQueryWrapper<SysTenant>().eq(SysTenant::getId, businessUtil.getTenantId()));
        return ResponseData.success(tenant.getContractSignImg());
    }


    @ApiOperation(value = "合同签章图片编辑")
    @PostMapping("/contractSigning/update")
    public ResponseData updateContractSigning(@RequestBody Dict dict)  {

        Object contractSignImg = dict.get("contractSignImg");
        boolean update = sysTenantService.update(
                new LambdaUpdateWrapper<SysTenant>()
                        .set(SysTenant::getContractSignImg, contractSignImg)
                        .eq(SysTenant::getId, businessUtil.getTenantId())
        );
        //if (!update) {
        //    throw new CustomException("更新合同签章失败");
        //}
        return ResponseData.success(contractSignImg);
    }


    //</editor-fold>


}
